<template>
    <up-list>
        <up-empty :iconSize="150" text="当前暂无企业信息" v-if="list.length === 0"></up-empty>
        <up-list-item v-for="item in list" :key="item.entName">
            <up-cell :title="item.entName"></up-cell>
        </up-list-item>
    </up-list>
    <div class="btn_box">
        <up-button type="primary" @click="openOrCancelModal">+加入企业</up-button>
    </div>

    <up-modal :show="show" title="加入企业" showCancelButton :closeOnClickOverlay="true" @cancel="openOrCancelModal"
        @confirm="confirmAdd" @close="openOrCancelModal">
        <up-form label-width="60px">
            <up-form-item label="企业码">
                <up-input v-model="relateEntCode" border="none" placeholder="请输入企业码"></up-input>
            </up-form-item>
        </up-form>
    </up-modal>

    <up-toast ref="uToastRef"></up-toast>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { Entlist, linkEnt } from '@/api/driver'
import { getEnt,linkEnt as linkCaptainEnt } from '@/api/captain'
import {
    useUserStore
} from '@/store/modules/user'
import {
    storeToRefs
} from "pinia"


/* hooks */
const {
    role
} = storeToRefs(useUserStore())

/* 数据 */
const uToastRef = ref<any>(null)
const list = reactive<any[]>([])
const show = ref(false)
const relateEntCode = ref('')


/* 函数 */
const confirmAdd = async () => {
    if (!relateEntCode.value) {
        uToastRef.value.show({
            position: 'top',
            message: '请输入企业码',
            type: 'warning'
        })
        return
    }
    uToastRef.value.show({
        message: '正在提交申请',
        type: 'loading',
        duration: -1
    })
    let fn = null
    if(role.value === 'driver'){
        fn = linkEnt
    }else{
        fn = linkCaptainEnt
    }
    let res = await fn(relateEntCode.value)
    uToastRef.value.hide()
    if (res.success) {
        openOrCancelModal()
        uToastRef.value.show({
            position: 'top',
            message: '操作成功',
            type: 'success',
            duration: 1000,
            complete() {
                init()
            }
        })
    }
}
// 开启关闭弹窗
const openOrCancelModal = () => {
    show.value = !show.value
}
// 获取列表
const getList = async () => {
    uToastRef.value.show({
        message: '正在获取企业列表',
        type: 'loading',
        duration: -1
    })
    let fn = null
    if (role.value === 'driver') {
        fn = Entlist
    } else {
        fn = getEnt
    }
    let res = await fn({ limit: 100 })
    uToastRef.value.hide()
    if (res.success) {
        list.push(...res.data)
    }
}
// 初始化封装
const init = async () => {
    list.length = 0
    await getList()
}


/* 钩子 */
onMounted(async () => {
    await init()
})
</script>

<style lang="scss" scoped>
.btn_box {
    position: fixed;
    bottom: 20px;
    left: 5%;
    width: 90%;
    z-index: 100;
}
</style>